#include "crow_all.h"
#include <iostream>
#include <string>
#include <unordered_map>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
using namespace std;

unordered_map<string, string> m;
boost::shared_mutex m_mutex;

int main() {
    crow::SimpleApp app;

    CROW_ROUTE(app, "/")([]{
        return "<h1>A Simple K/V Cache over HTTP</h1>";
    });

    CROW_ROUTE(app, "/get/<string>")([&m](string key){
        boost::shared_lock<boost::shared_mutex> lock(m_mutex);
	    return m[key];
    });

    CROW_ROUTE(app, "/set/<string>/<string>")([&m](string key, string value){
        boost::unique_lock<boost::shared_mutex> lock(m_mutex);
        m[key] = value;
        return "SUCC";
    });

    CROW_ROUTE(app, "/del/<string>")([&m](string key){
	    boost::unique_lock<boost::shared_mutex> lock(m_mutex);
	    unordered_map<string, string>::iterator iter = m.begin();
	    iter = m.find(key);
	    if(iter != m.end()) {
	        m.erase(iter);
            return "SUCC";
        }
        return "FAIL";
    });

    app.port(18080)
	.multithreaded()
	.run();
}
